package com.ling.ling_push.pusher;

import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;

import com.ling.ling_push.MainActivity;
import com.example.my_push.jni.PushNative;
import com.ling.ling_push.params.VideoParam;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

class VideoPusher extends Pusher implements SurfaceHolder.Callback, Camera.PreviewCallback{
    private SurfaceHolder surfaceHolder;
    private PushNative pushNative;
    private VideoParam videoParam;
    private Camera mCamera;
    private byte[] buffers;
    private boolean isPushing = false;
    public VideoPusher(SurfaceHolder surfaceHolder, VideoParam videoParam, PushNative pushNative) {
        this.surfaceHolder = surfaceHolder;
        this.pushNative = pushNative;
        this.videoParam = videoParam;
        surfaceHolder.addCallback(this);
    }
    @Override
    public void startPush() {
        isPushing=true;
    }

    @Override
    public void stopPush() {
        isPushing = false;
    }

    @Override
    public void release() {
        stopPreview();
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        startPreview();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    /**
     * 切换摄像头
     */
    public void switchCamera() {
        if(videoParam.getCameraId() == Camera.CameraInfo.CAMERA_FACING_BACK){
            videoParam.setCameraId(Camera.CameraInfo.CAMERA_FACING_FRONT);
        }else{
            videoParam.setCameraId(Camera.CameraInfo.CAMERA_FACING_BACK);
        }
        //重新预览
        stopPreview();
        startPreview();
    }
    /**
     * 开始预览
     */
    private void startPreview() {
        //SurfaceView初始化完成，开始相机预览
        mCamera = Camera.open(videoParam.getCameraId());
        //配置Camera属性
        Camera.Parameters parameters=  mCamera.getParameters();
        // parameters.setFlashMode("off"); // 无闪光灯
        //设置预览数据格式
        parameters.setPreviewFormat(ImageFormat.NV21);
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
        //预览画面宽高
        setPreviewSice(parameters,videoParam.getWidth(),videoParam.getHeight());
        setPreviewOrieentation(parameters);
        mCamera.setParameters(parameters);
        videoParam.setHeight(mCamera.getParameters().getPreviewSize().height);
        videoParam.setWidth(mCamera.getParameters().getPreviewSize().width);
        //获取预览图像数据
       // buffers = new byte[videoParam.getWidth() * videoParam.getHeight() * 4];
        //数据缓冲区
        buffers =new byte[videoParam.getWidth()*videoParam.getHeight()*3/2];
        mCamera.addCallbackBuffer(buffers);
        mCamera.setPreviewCallbackWithBuffer(this);
        try {
            mCamera.setPreviewDisplay(surfaceHolder);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mCamera.startPreview();
        // 【调试】设置后的图片大小和预览大小以及帧率打印出来
        //Camera.Size csize = mCamera.getParameters().getPreviewSize();//帧率的大小
        videoParam.setHeight(mCamera.getParameters().getPreviewSize().height);
        videoParam.setWidth(mCamera.getParameters().getPreviewSize().width);
}

    /**
     * 停止预览
     */
    private void stopPreview() {
        if(mCamera != null){
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        if(mCamera != null){
            mCamera.addCallbackBuffer(buffers);
        }

        if(isPushing){
           // Log.e("收到","摄像头数据:"+data.length);
            //回调函数中获取图像数据，然后给Native代码编码
             pushNative.fireVideo(data);
        }
    }
    private void setPreviewOrieentation(Camera.Parameters parameters) {
        Camera.CameraInfo info =
                new Camera.CameraInfo();
        Camera.getCameraInfo(videoParam.getCameraId(), info);
        int rotation = MainActivity.GetActivity().getWindowManager().getDefaultDisplay()
                .getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0: degrees = 0; break;
            case Surface.ROTATION_90: degrees = 90; break;
            case Surface.ROTATION_180: degrees = 180; break;
            case Surface.ROTATION_270: degrees = 270; break;
        }
        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        mCamera.setDisplayOrientation(result);
    }
    private void setPreviewSice(Camera.Parameters parameters,int mWidth,int mHeight) {
        //获取摄像头支持的宽，高
        List<Camera.Size> supportedPreviewSizes=parameters.getSupportedPreviewSizes();
        Camera.Size size=supportedPreviewSizes.get(0);
        Log.d("setPreviewSice","支持"+size.width+"X"+size.height);
        //选择一个最小的支持分辨率
        int m=Math.abs(size.height*size.width-mWidth*mHeight);
        supportedPreviewSizes.remove(0);
        Iterator<Camera.Size> iterator=supportedPreviewSizes.iterator();
        while (iterator.hasNext()){
            Camera.Size next=iterator.next();
            Log.d("setPreviewSice","支持"+size.width+"X"+size.height);
            int n=Math.abs(next.height*next.width-mWidth*mHeight);
            if (n<m){
                m=n;
                size=next;
            }
        }
        mWidth=size.width;
        mHeight=size.height;
        parameters.setPreviewSize(mWidth,mHeight);
        Log.d("setPreviewSice","设置分辨率：width"+size.width+"height"+size.height);
    }

    public VideoParam  getVideoParam() {
        return this.videoParam;
    }


}
